<template>
  <div>
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <select-submit-batch
          placeholder="提交批次"
          @change="getData()"
          @clear="getData()"
          clearable
          v-model="params['batch_no.eq']"
        ></select-submit-batch>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="提交日期(开始)"
          end-placeholder="提交日期(截止)"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="提交状态"
          clearable
          number-key
          :options="enumSubmitStatus"
          v-model="params['project_apply_status.eq']"
          @change="getData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-dowload" @click="exportExcel('存量-项目申报')">导出</el-button>
      </el-form-item>

      <el-form-item class="float-right">
        <el-button
          icon="el-icon-folder-checked"
          type="primary"
          class="btn-long"
          v-permission="{ scope: 'indoneBI' }"
          @click="handleSubmit"
        >
          提交
        </el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:person="scope">
        <!-- <small>{{ scope.row.submit_client_name }}</small> -->
        <div>{{ scope.row.submit_person_name }}</div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <submit-edit-dialog
      :visible.sync="submitVisible"
      @success="handleSubmitSuccess"
      :product-id="productId"
      @dismiss="handleSubmitDismiss"
    ></submit-edit-dialog>

    <submit-list-dialog
      :visible.sync="viewVisible"
      :batch-data="viewBatchData"
    ></submit-list-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  enumSubmitStatus,
  enumSubmitStatusStyle,
} from '@/bank/views/business/limit/history/submit/mixins'
import { lastPickerShortcuts } from '@/common/plugins/tools/date'

import SelectSubmitBatch from '@/bank/views/business/industry/history/submit/SelectSubmitBatch'
import SubmitEditDialog from '@/bank/views/business/industry/history/submit/SubmitEditDialog'
import SubmitListDialog from '@/bank/views/business/industry/history/submit/SubmitListDialog'
import { getAddressNextValue } from '@/common/api/address'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
export default {
  components: {
    SelectSubmitBatch,
    SubmitEditDialog,
    SubmitListDialog,
  },
  props: {},
  data() {
    return {
      enumSubmitStatus,

      loading: false,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'batch_no.eq': '',
        'project_apply_status.eq': '',
        'channel_type.eq': 0,
        'is_rural_dev.eq': 1,
      },
      order: {
        create_time: 'desc',
      },
      tableName: 'project_apply_batch',
      tableColumns: [
        { attrs: { label: '提交批次', prop: 'batch_no', align: 'center' } },
        { attrs: { label: '提交数量', prop: 'project_count', align: 'center' } },
        { attrs: { label: '项目总额(万元)', prop: 'project_funds', align: 'center' } },
        {
          attrs: { label: '审核机构', prop: 'person', align: 'center' },
          process: () => '省农担',
        },
        {
          attrs: { label: '提交日期', prop: 'create_time', align: 'center' },
        },
        {
          attrs: { label: '提交银行', prop: 'submit_client_name', align: 'center' },
        },
        {
          attrs: { label: '提交人', prop: 'submit_person_name', align: 'center' },
          // slot: 'person',
        },
        {
          attrs: { label: '提交状态', prop: 'submitStatusLabel', align: 'center' },
          process: (_, row) => ({ attrs: { class: `text-${row.submitStatusStyle}` } }),
        },
        {
          attrs: { label: '操作', align: 'center' },
          operations: [{ name: '查看', event: this.handleView }],
        },
      ],
      tableData: [],
      tableCount: 0,

      // 提交时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },

      // 提交
      submitVisible: false,

      // 查看
      viewVisible: false,
      viewBatchData: {},
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'clientId', 'org']),
    productId() {
      return this.$route.query.id
    },
    isSubmit() {
      return this.user.scopes.includes('indoneBI')
    },
    isSYSTEM() {
      // 系统后台查所有
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {},
  created() {
    if (!this.isSYSTEM) {
      const { queryAddressCode, clientOrgClassType } = this.user
      if (this.isSubmit) {
        this.params.orWhereAndTemplate = 2
        this.params['orWhereAnd.submit_client_id.eq'] = this.clientId
        this.params['orWhereAnd.bank_type.in'] = clientOrgClassType
        this.params['orWhereAnd.submit_client_address_code.gt'] = queryAddressCode
        this.params['orWhereAnd.submit_client_address_code.lt'] =
          getAddressNextValue(queryAddressCode)
        this.params['orWhereAnd.bank_type.eq'] = clientOrgClassType
      } else {
        this.params['submit_person.eq'] = this.userId
      }
    }

    this.getData()
  },
  mounted() {},
  methods: {
    async exportExcel(filename) {
      const exportTable = this.tableColumns.filter(item => !item.operations && !item.hidden)
      const header = {}

      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}3`] = { font: { bold: true } }
        // headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })

      let data = []

      this.exportLoading = true
      const { index, size, ...params } = this.params
      const res = await this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      data = (res.data || []).map((item, index) => {
        return {
          index: index + 1,
          ...this.dataAdapter(item),
        }
      })

      const title1 = {
        index: '黔农十二贷',
      }
      excelJsonExport({
        columns,
        data: [title1, title1, title1, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:AE3'],
        cols: [{ wch: 6 }],
        cellStyles: {
          A1: {
            alignment: { horizontal: 'left' },
            font: { bold: true, sz: 24 },
          },
          A2: { alignment: { horizontal: 'left' }, font: { bold: true } },
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
    getData(index = 1) {
      if (!this.user.queryAddressCode) {
        return this.$message.error('该账户没有配置地址，无法查询所需提交项目')
      }
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = (data.data || []).map(this.dataAdapter)
          this.tableCount = data.totalCount || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.person = '省农担'
      item.project_apply_status = +(item.project_apply_status || 0)
      item.submitStatusLabel = enumSubmitStatus[item.project_apply_status]
      item.submitStatusStyle = enumSubmitStatusStyle[item.project_apply_status]

      return item
    },

    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['create_time.gte'] = start
        this.params['create_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['create_time.gte'] = ''
        this.params['create_time.lte'] = ''
      }
      this.getData()
    },

    handleView(row = {}) {
      this.viewBatchData = row
      this.viewVisible = true
    },

    handleSubmit() {
      this.submitVisible = true
    },
    handleSubmitDismiss() {
      this.submitVisible = false
    },

    handleSubmitSuccess() {
      this.submitVisible = false
      this.$store.dispatch('getTaskCountIndustry', { type: 0, id: this.productId })
      this.getData()
    },
  },
}
</script>

<style lang="scss" scoped>
.search-sw {
  width: 130px;
}
</style>
